package com.zhang.authoritycenter.security.jwt;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import com.zhang.infrastructure.model.constant.redis.RedisConstant;
import com.zhang.infrastructure.model.token.KingHoodPrincipal;
import com.zhang.authoritycenter.common.util.KingHoodPrincipalBuilder;
import com.zhang.authoritycenter.common.properties.BaseProperties;
import com.zhang.redis.util.RedisManager;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.Key;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 实现配置可以实时刷新
 * */
@RequiredArgsConstructor
@Component
public class TokenProvider implements InitializingBean {

   private final Logger log = LoggerFactory.getLogger(TokenProvider.class);

   private static final String AUTHORITIES_KEY = "auth";
   private static final String INFO_KEY = "info";
   private final RedisManager<String> redisManager;
   private Key key;

   @Resource
   private BaseProperties baseProperties;

   @Override
   public void afterPropertiesSet() {
      byte[] keyBytes = Decoders.BASE64.decode(baseProperties.getBase64Secret());
      this.key = Keys.hmacShaKeyFor(keyBytes);
   }

   public String createToken(Authentication authentication, boolean rememberMe) {
      String authorities = authentication.getAuthorities().stream()
         .map(GrantedAuthority::getAuthority)
         .collect(Collectors.joining(","));

      long now = (new Date()).getTime();
      Date validity;
      if (rememberMe) {
         validity = new Date(now + baseProperties.getTokenValidityInSecondsForRememberMe());
      } else {
         validity = new Date(now + baseProperties.getTokenValidityInSeconds());
      }

      return Jwts.builder().setIssuer("inner").setAudience("5566")
         .setSubject(authentication.getName())
         .claim(AUTHORITIES_KEY, authorities)
         .signWith(key, SignatureAlgorithm.HS512)
         .setExpiration(validity)
         .compact();
   }

   private static String getInfoEncode(String info) {
      if (StringUtils.isBlank(info)) {
         info = "{}";
      }
      return Base64.encode(info.getBytes());
   }

   public String getToken(String issuer,String audience,String subject, String info,String authorities,int tokenValidityInSeconds){

      String infoEncode = getInfoEncode(info);

      Date validity = DateUtil.offsetSecond(new Date(),tokenValidityInSeconds);

      return Jwts.builder()
              .setIssuer(issuer)
              .setAudience(audience)
              .setSubject(subject)
              .claim(INFO_KEY, infoEncode)
              .claim(AUTHORITIES_KEY, authorities)
              .signWith(key, SignatureAlgorithm.HS512)
              .setExpiration(validity)
              .compact();
   }

   public Authentication getAuthentication(String token) {
      Claims claims = Jwts.parser()
         .setSigningKey(key)
         .parseClaimsJws(token)
         .getBody();

      // 发行
      String issuer = claims.getIssuer();
      // 观众
      String audience = claims.getAudience();
      // 主题
      String subject = claims.getSubject();
      String auths = claims.get(AUTHORITIES_KEY).toString();
      String info = claims.get(INFO_KEY).toString();
      Date expiration = claims.getExpiration();

      Collection<? extends GrantedAuthority> authorities =
         Arrays.stream(auths.split(","))
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toList());

      KingHoodPrincipal principal = KingHoodPrincipalBuilder.getInstance(issuer, audience, subject,expiration,new String(Base64.decode(info)));
//      User principal = new User(claims.getSubject(), "", authorities);

      return new UsernamePasswordAuthenticationToken(principal, token, authorities);
   }

   public boolean validateToken(String authToken) {
      try {
         Jwts.parser().setSigningKey(key).parseClaimsJws(authToken);
         // 判断是否退出登录
         String value = redisManager.keyValue().get(RedisConstant.LOGOUT_PREFIX + authToken);
         if(Objects.nonNull(value)){
            return false;
         }
         return true;
      } catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) {
         log.info("Invalid JWT signature.");
         log.trace("Invalid JWT signature trace: {}", e);
      } catch (ExpiredJwtException e) {
         log.info("Expired JWT token.");
         log.trace("Expired JWT token trace: {}", e);
      } catch (UnsupportedJwtException e) {
         log.info("Unsupported JWT token.");
         log.trace("Unsupported JWT token trace: {}", e);
      } catch (IllegalArgumentException e) {
         log.info("JWT token compact of handler are invalid.");
         log.trace("JWT token compact of handler are invalid trace: {}", e);
      }
      return false;
   }
}
